package cn.iocoder.yudao.module.system.service.userassetscode;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.system.controller.admin.userassetscode.vo.UserAssetsCodeUsageLogPageReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.userassetscode.UserAssetsCodeUsageLogDO;
import cn.iocoder.yudao.module.system.dal.mysql.userassetscode.UserAssetsCodeUsageLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_ASSETS_CODE_USAGE_LOG_NOT_EXISTS;

/**
 * 兑换码使用记录 Service 实现类
 *
 * @author 系统
 */
@Service
@Validated
@Slf4j
public class UserAssetsCodeUsageLogServiceImpl implements UserAssetsCodeUsageLogService {

    @Resource
    private UserAssetsCodeUsageLogMapper userAssetsCodeUsageLogMapper;

    @Override
    public PageResult<UserAssetsCodeUsageLogDO> getUserAssetsCodeUsageLogPage(UserAssetsCodeUsageLogPageReqVO pageReqVO) {
        return userAssetsCodeUsageLogMapper.selectPage(pageReqVO);
    }

    @Override
    public UserAssetsCodeUsageLogDO getUserAssetsCodeUsageLog(Long id) {
        UserAssetsCodeUsageLogDO usageLog = userAssetsCodeUsageLogMapper.selectById(id);
        if (usageLog == null) {
            throw exception(USER_ASSETS_CODE_USAGE_LOG_NOT_EXISTS);
        }
        return usageLog;
    }

    @Override
    public List<UserAssetsCodeUsageLogDO> getUserAssetsCodeUsageLogByUserId(Long userId) {
        return userAssetsCodeUsageLogMapper.selectByUserId(userId);
    }

    @Override
    public List<UserAssetsCodeUsageLogDO> getUserAssetsCodeUsageLogByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return userAssetsCodeUsageLogMapper.selectByTimeRange(startTime, endTime);
    }

    @Override
    public Long countUserAssetsCodeUsage(Long userId) {
        return userAssetsCodeUsageLogMapper.countByUserId(userId);
    }

    @Override
    public Long createUserAssetsCodeUsageLog(@Valid UserAssetsCodeUsageLogDO usageLog) {
        userAssetsCodeUsageLogMapper.insert(usageLog);
        return usageLog.getId();
    }

    @Override
    public void updateUserAssetsCodeUsageLog(@Valid UserAssetsCodeUsageLogDO usageLog) {
        // 校验存在
        validateUserAssetsCodeUsageLogExists(usageLog.getId());
        // 更新
        userAssetsCodeUsageLogMapper.updateById(usageLog);
    }

    private void validateUserAssetsCodeUsageLogExists(Long id) {
        if (userAssetsCodeUsageLogMapper.selectById(id) == null) {
            throw exception(USER_ASSETS_CODE_USAGE_LOG_NOT_EXISTS);
        }
    }
}